package com.hog.datasource;

import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

import java.util.Properties;

/**
 * Mybatis Mapper扫描配置类
 *
 * @author 糖先森
 * @date 2018年03月29日
 * @since JDK 1.8
 */
@Configuration
//TODO 注意，由于MapperScannerConfigurer执行的比较早，所以必须有下面的注解
@AutoConfigureAfter(HogDataSourceConfig.class)
public class HogMapperConfig implements EnvironmentAware {
    public static final String BEAN_NAME_HOG_MAPPER_SCANNER_CONFIG = "hogMapperScannerConfigurer";
    private String basePackage;

    @Bean(name = BEAN_NAME_HOG_MAPPER_SCANNER_CONFIG)
    public MapperScannerConfigurer mapperScannerConfigurer() {
        tk.mybatis.spring.mapper.MapperScannerConfigurer mapperScannerConfigurer = new tk.mybatis.spring.mapper.MapperScannerConfigurer();
        mapperScannerConfigurer.setSqlSessionTemplateBeanName(HogDataSourceConfig.BEAN_NAME_HOG_SQL_SESSION_TEMPLATE);
        mapperScannerConfigurer.setBasePackage(basePackage);
        Properties properties = new Properties();
        properties.setProperty("ORDER", "BEFORE");
        properties.setProperty("mappers", "tk.mybatis.mapper.common.Mapper,tk.mybatis.mapper.common.IdsMapper");
        mapperScannerConfigurer.setProperties(properties);
        return mapperScannerConfigurer;
    }

    public void setEnvironment(Environment environment) {
        this.basePackage = environment.getProperty("mybatis.basePackage");
    }
}